package com.rc.web.service.impl;


import com.rc.web.client.TtsWebSocketClient;
import com.rc.web.utils.AudioDecoder;
import com.rc.web.utils.VivoAuth;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;

import java.net.URI;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 调用tts接口
 * 文字转语音的主要方法
 */
// TODO: 2025/3/25 当前端转语音是文字不能超过 2048/3的682个中文，需要补充前端的文本字节的判断保护
@Service
public class TtsService {

    private final String API_URL = "wss://api-ai.vivo.com.cn/tts";
    private final String APP_ID = "2025985389";
    private final String APP_KEY = "eAkRKtYXOawsmtVv";

    private final String ENGINE_ID = "tts_replica";

    public byte[] generateAudio(String text,String vcn,String engineid,String timbre) throws Exception {
        Map<String, String> params = new HashMap<>();
        if(vcn.equals("0")){
            params.put("engineid",engineid);
        }else {
            params.put("engineid", ENGINE_ID);
        }
        params.put("system_time", String.valueOf(System.currentTimeMillis() / 1000));
        params.put("user_id", "123"); // 用户 ID
        params.put("model", "unknown"); // 手机外部型号
        params.put("product", "unknown"); // 内部机型名
        params.put("package", "unknown"); // 应用包名
        params.put("client_version", "unknown"); // 应用版本号
        params.put("system_version", "unknown"); // 手机系统版本号
        params.put("sdk_version", "unknown"); // SDK 版本号
        params.put("android_version", "unknown"); // Android 系统版本号

        String queryString = buildQueryString(params);
        HttpHeaders headers = VivoAuth.generateAuthHeaders(APP_ID, APP_KEY, "GET", "/tts", queryString);

        URI uri = new URI(API_URL + "?" + queryString);
        TtsWebSocketClient client = new TtsWebSocketClient(uri, text, headers, vcn ,timbre);

        client.connectBlocking();
        byte[] pcmData = client.getAudioData();
        return AudioDecoder.pcmToWav(pcmData);
    }

    private String buildQueryString(Map<String, String> params) {
        return params.entrySet().stream()
                .map(entry -> entry.getKey() + "=" + URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8))
                .collect(Collectors.joining("&"));
    }
}